import 'dart:convert';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_view/photo_view.dart';
import 'dart:io';
import '../../AppConfig/Config.dart';
import 'package:image/image.dart' as img;

import '../../AppConfig/LocalStorage.dart';
import '../../Tabbar/TabbarView.dart';
import '../../http/api.dart';
class CancelWaybill extends StatefulWidget {
  const CancelWaybill({super.key, required this.billMap});
  final Map billMap;
  @override
  State<CancelWaybill> createState() => _CancelWaybillState();
}

class _CancelWaybillState extends State<CancelWaybill> {
  List reasonList=["货主临时不需要用车了","货主另找车","货物信息与实际不符","天气原因","禁区限行","联系不上货主","车辆与要求不符","来不及装货","临时无法装货","其他"];
  String chooseReason="";
  List imagePaths = [];
  List base64List=[];
  String? checkImage;
  int chkecType=-1;
  String seasonStr ="";
  final ImagePicker picker = new ImagePicker();
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title:Text( "申请取消运单",style: TextStyle(fontWeight: FontWeight.w300),),
        backgroundColor: Colors.white,
        centerTitle: true,
      ),
      body: Column(
        children: [
          Expanded(child: ListView(
            children: [
                  Container(
                    width: screenSize.width,
                    height: 30.h,
                    color: Color.fromRGBO(251, 236, 228, 1),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("1.提交申请",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),),
                        Text(">",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.5)),),
                        Text(">",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85)),),
                        Text("2.货主同意",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),),
                        if(widget.billMap['deposit'].toString()!="0")
                          Row(
                            children: [
                              Text(">",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.5)),),
                              Text(">",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85)),),
                              Text("3.订金退还给您",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),),
                            ],
                          ),

                      ],
                    ),
                  ),
              if(widget.billMap['deposit'].toString()!="0")
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(left: 12.w, top: 16.h,bottom: 16.h,right: 11.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                  Text("申请取消运单退还订金",style: TextStyle(color: Colors.black,fontSize: 14.sp)),
                  Text("¥"+widget.billMap['deposit'],style: TextStyle(color: MyColors.themeColor,fontSize: 18.sp),),
                ],),
              ),
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(left: 12.w, top: 16.h,bottom: 16.h,right: 12.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("请补充申请原因",style: TextStyle(color: Colors.black),),
                    SizedBox(height: 10.h,),
                    Wrap(
                      spacing: 8.0, // 两个Container之间的水平间距
                      runSpacing: 10.h, // 行与行之间的垂直间距
                      children: reasonList.map((length) {
                        bool isSelected = chooseReason.contains(length)?? false;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                chooseReason="";
                              } else {
                                // 如果未被选中且未达到最大选择数量，则添加
                                chooseReason=length;
                              }
                            });
                          },
                          child: Container(
                              margin:EdgeInsets.only(left: 8.w,right: 8.w),
                            constraints: BoxConstraints(maxHeight: 30.0, maxWidth: 130.w),
                            decoration: BoxDecoration(
                            color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor,
                            borderRadius: BorderRadius.circular(3.0),
                          ),
                          child: Center(
                            child: Text(
                              length,
                              style: TextStyle(fontSize: 12.sp, color: isSelected ? MyColors.themeColor : Colors.black),
                            ),
                          ),
                        ),
                        );
                      }).toList(),
                    ),
                    SizedBox(height: 10.h,),
                    BrnInputText(
                      maxHeight: 200.h,
                      minHeight: 100.h,
                      minLines: 1,
                      maxLength: 100,
                      bgColor:Color.fromRGBO(248, 248, 248, 1),
                      textString:seasonStr,
                      textInputAction: TextInputAction.newline,
                      maxHintLines: 20,
                      hint: '请描述具体原因，有助于货主更快识别并处理',
                      padding: EdgeInsets.fromLTRB(20, 10, 20, 14),
                      onTextChange: (text) {

                        setState(() {
                          seasonStr=text;
                        });
                      },
                      onSubmit: (text) {
                        print(text);
                      },
                    ),
                  ],
                ),
              ),
            Container(
              margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
              padding: EdgeInsets.only(left: 12.w, top: 10.h,bottom: 19.h,right: 12.w),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("证明图片",style: TextStyle(color: Colors.black),),
                  Text("最多上传3张",style: TextStyle(color: MyColors.hintColor,fontSize: 12.sp),),
                  Container(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Wrap(
                        spacing: 8.0,
                        runSpacing: 8.0,
                        children: [
                          ...imagePaths.map((path) => buildImageWidget(path)).toList(),
                          buildAddImageWidget(1),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            )
            ],
          ),
          ),
          Container(
            height: 80.h,
            padding: EdgeInsets.only(left: 15.w,right: 15.w,top: 10.h,bottom: 40.h),
            child: BrnSmallMainButton(
              title: '提交申请',
              bgColor: MyColors.themeColor,
              textColor: Colors.white,
              radius: 30,
              width: screenSize.width-30.w,
              fontWeight: FontWeight.w600,
              fontSize: 16.sp,
              onTap: () async {
                String? token = await TokenManager.getToken();
                dio.interceptors.add(InterceptorsWrapper(
                    onRequest: (options, handler) {
                      options.headers["satoken"] = token;
                      return handler.next(options);
                    }
                ));
                dio.post(
                  MyServiceUrl.header +
                      'api/waybill/waybill/common/cancelWaybill',
                  data: {
                    "waybillId":widget.billMap['waybillId'],
                    "cancelStatus":0,
                    "depositType":0,
                    "cancelType": 3,
                    "cancelMessageId": "0",
                    "cancelMessage":chooseReason,
                  },
                  options: Options(
                    sendTimeout: Duration(seconds: 2),
                    receiveTimeout: Duration(seconds: 50),
                  ),
                  onSendProgress: (a, b) => print('send ${a / b}'),
                  onReceiveProgress: (a, b) =>
                      print('received ${a / b}'),
                )
                    .then((r) {
                  setState(() {
                    print(r);
                    Map<String, dynamic> jsonMap = json.decode(
                        r.toString());
                    // 获取code和data
                    String code = jsonMap['code'].toString();
                    if (code == "200") {
                      BrnToast.show("操作成功", context);
                      Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
                      ); // 点击返回箭头时返回到

                    } else {
                      BrnToast.show(jsonMap['msg'], context);
                    }
                  });
                }).catchError((error) {
                  print(error);
                  ;
                });
              },
            ),
          )
        ],
      ),
    );
  }
  Widget buildImageWidget(String imagePath) {
    return Container(
      width: 85.w,
      height: 85.h,
      child: Stack(
        children: [
          GestureDetector(
            onTap: () {
              // 处理点击查看图片的逻辑
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ImageViewer(imagePath),
                ),
              );
            },
            child: Container(
              width: 85.w,
              height: 85.h,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: FileImage(File(imagePath)),
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(8.0),
              ),
            ),
          ),

          Positioned(
            top: 0,
            right: 0,
            child: GestureDetector(
              child: Icon(Icons.highlight_off,size: 30,color: MyColors.authTipColor,),
              onTap: () {
                setState(() {
                  imagePaths.remove(imagePath);
                });
              },
            ),
          ),
        ],
        alignment: Alignment.center,
      ),
    );





  }

  Widget buildAddImageWidget(int checkType) {
    return GestureDetector(
        onTap: () async {
          if (imagePaths.length!=3) {
            setState(() {
              chkecType = checkType;
            });
            showModalBottomSheet(
                context: context, builder: (BuildContext context) {
              return Container(
                color: Colors.white,
                child:
                Stack(

                  children: [

                    Column(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,

                      children: [

                        SizedBox(height: 8.h,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            SizedBox(width: 30.w,),
                            Text("上传照片", style: TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.w600,
                                fontSize: 18.sp),),
                            IconButton(onPressed: () {
                              Navigator.of(context).pop();
                            }, icon: Icon(Icons.close)),
                          ],
                        ),


                        SizedBox(height: 8.h,),
                        Row(
                          children: [
                            SizedBox(width: 38.w,),
                            GestureDetector(
                              child: Column(
                                children: [
                                  Image.asset(
                                    "lib/Images/Authentication/相册icon.png",
                                    width: 35.w, height: 35.h,),
                                  Text("相册",
                                    style: TextStyle(color: Colors.black),),

                                ],

                              ),
                              onTap: () async {
                                Navigator.of(context).pop();
                                final pickedFile = await picker.pickImage(
                                    source: ImageSource.gallery);

                                if (pickedFile != null) {
                                  setState(() {
                                    checkImage = pickedFile.path;
                                    printImageMemorySize(File(checkImage!));
                                    print(checkImage);
                                    compressImage(File(checkImage!));
                                  });
                                }
                              },
                            ),

                            SizedBox(width: 38.w,),
                            GestureDetector(
                              child: Column(
                                children: [
                                  Image.asset(
                                    "lib/Images/Authentication/拍照icon.png",
                                    width: 35.w, height: 35.h,),
                                  Text("拍照",
                                    style: TextStyle(color: Colors.black),),

                                ],

                              ),
                              onTap: () async {
                                Navigator.of(context).pop();
                                final pickedFile = await picker.pickImage(
                                    source: ImageSource.camera);

                                if (pickedFile != null) {
                                  setState(() {
                                    checkImage = pickedFile.path;
                                    printImageMemorySize(File(checkImage!));
                                    print(checkImage);
                                    compressImage(File(checkImage!));
                                  });
                                }
                              },
                            ),

                          ],
                        ),
                        SizedBox(height: 40.h,),
                      ],

                    ),

                  ],

                ),
              );
            });
          }else{
            BrnToast.show("最多添加3张", context);
          }

        },
        child:imagePaths.length!=3? Image.asset("lib/Images/OrderList/图片管理上传照片.png",width: 85.w,height: 85.h,):Container()
    );
  }

  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);
    base64List.add(base64String);
    setState(() {
      imagePaths.add(checkImage.toString());

    });
  }


}
class ImageViewer extends StatelessWidget {
  final String imagePath;

  ImageViewer(this.imagePath);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          // 当点击大图时，返回上一个页面
          Navigator.pop(context);
        },
        child: PhotoView(
          imageProvider: FileImage(File(imagePath)),
          minScale: PhotoViewComputedScale.contained * 0.8,
          maxScale: PhotoViewComputedScale.covered * 2,
        ),
      ),
    );
  }

}
